package com.example.HaiDLaobackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.HaiDLaobackend.common.ApiResponse;
import com.example.HaiDLaobackend.common.JwtUtil;
import com.example.HaiDLaobackend.entity.RefundRequestEntity;
import com.example.HaiDLaobackend.entity.UserAddressEntity;
import com.example.HaiDLaobackend.entity.UserCouponEntity;
import com.example.HaiDLaobackend.entity.UserEntity;
import com.example.HaiDLaobackend.entity.UserFavoriteEntity;
import com.example.HaiDLaobackend.service.OrderService;
import com.example.HaiDLaobackend.service.RefundRequestService;
import com.example.HaiDLaobackend.service.UserAddressService;
import com.example.HaiDLaobackend.service.UserCouponService;
import com.example.HaiDLaobackend.service.UserFavoriteService;
import com.example.HaiDLaobackend.service.UserService;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/users")
public class UserController {

	private final UserService userService;
    private final OrderService orderService;
    private final UserFavoriteService userFavoriteService;
    private final UserCouponService userCouponService;
    private final UserAddressService userAddressService;
    private final RefundRequestService refundRequestService;

	public UserController(UserService userService,
                         OrderService orderService,
                         UserFavoriteService userFavoriteService,
                         UserCouponService userCouponService,
                         UserAddressService userAddressService,
                         RefundRequestService refundRequestService) {
		this.userService = userService;
        this.orderService = orderService;
        this.userFavoriteService = userFavoriteService;
        this.userCouponService = userCouponService;
        this.userAddressService = userAddressService;
        this.refundRequestService = refundRequestService;
	}

    public static class UpdateProfileRequest {
        private String nickname;
        private String avatarUrl;
        private String phone;
        private String oldPassword;
        private String newPassword;

        public String getNickname() { return nickname; }
        public void setNickname(String nickname) { this.nickname = nickname; }
        public String getAvatarUrl() { return avatarUrl; }
        public void setAvatarUrl(String avatarUrl) { this.avatarUrl = avatarUrl; }
        public String getPhone() { return phone; }
        public void setPhone(String phone) { this.phone = phone; }
        public String getOldPassword() { return oldPassword; }
        public void setOldPassword(String oldPassword) { this.oldPassword = oldPassword; }
        public String getNewPassword() { return newPassword; }
        public void setNewPassword(String newPassword) { this.newPassword = newPassword; }
    }

    @PutMapping("/profile")
    public ApiResponse<Map<String, Object>> updateProfile(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId,
                                                          @RequestBody UpdateProfileRequest body) {
        if (currentUserId == null) {
            return ApiResponse.error(401, "未登录");
        }
        UserEntity user = userService.getById(currentUserId);
        if (user == null) {
            return ApiResponse.error(404, "用户不存在");
        }
        if (body.getNickname() != null) user.setNickname(body.getNickname());
        if (body.getAvatarUrl() != null) user.setAvatarUrl(body.getAvatarUrl());
        if (body.getPhone() != null) user.setPhone(body.getPhone());

        if (body.getOldPassword() != null && body.getNewPassword() != null
            && !body.getOldPassword().isEmpty() && !body.getNewPassword().isEmpty()) {
            if (!body.getOldPassword().equals(user.getPassword())) {
                return ApiResponse.error(400, "原密码不正确");
            }
            user.setPassword(body.getNewPassword());
        }
        userService.updateById(user);

        Map<String, Object> result = new HashMap<>();
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
        userInfo.put("avatarUrl", user.getAvatarUrl());
        userInfo.put("phone", user.getPhone());
        result.put("userInfo", userInfo);
        return ApiResponse.ok(result);
    }
	public static class AuthRequest {
		@NotBlank
		private String username;
		@NotBlank
		private String password;

		public String getUsername() { return username; }
		public void setUsername(String username) { this.username = username; }
		public String getPassword() { return password; }
		public void setPassword(String password) { this.password = password; }
	}

	@PostMapping("/register")
	public ApiResponse<UserEntity> register(@Valid @RequestBody AuthRequest body) {
		UserEntity exists = userService.getOne(new LambdaQueryWrapper<UserEntity>()
			.eq(UserEntity::getUsername, body.getUsername()));
		if (exists != null) {
			return ApiResponse.error("用户名已存在");
		}
		UserEntity user = new UserEntity();
		user.setUsername(body.getUsername());
		user.setPassword(body.getPassword());
		user.setStatus(1);
		userService.save(user);
		return ApiResponse.ok(user);
	}

    @PostMapping("/login")
    public ApiResponse<Map<String, Object>> login(@Valid @RequestBody AuthRequest body) {
		UserEntity user = userService.getOne(new LambdaQueryWrapper<UserEntity>()
			.eq(UserEntity::getUsername, body.getUsername())
			.eq(UserEntity::getPassword, body.getPassword()));
		if (user == null) {
			return ApiResponse.error("用户名或密码错误");
		}
		Map<String, Object> data = new HashMap<>();
        String token = JwtUtil.generateToken(user.getId(), user.getUsername());
        data.put("token", token);
		data.put("user", user);
		return ApiResponse.ok(data);
	}

    @GetMapping("/profile")
    public ApiResponse<Map<String, Object>> profile(@RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) {
            return ApiResponse.error(401, "未登录");
        }
        UserEntity user = userService.getById(currentUserId);
        if (user == null) {
            return ApiResponse.error(404, "用户不存在");
        }
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", user.getId());
        userInfo.put("nickname", user.getNickname() != null ? user.getNickname() : user.getUsername());
        userInfo.put("avatarUrl", user.getAvatarUrl());
        userInfo.put("phone", user.getPhone());

        Map<String, Object> data = new HashMap<>();
        data.put("userInfo", userInfo);
        data.put("orderSummary", orderService.summaryByStatus(currentUserId));

        Map<String, Long> toolSummary = new HashMap<>();
        toolSummary.put("favorite", userFavoriteService.count(new LambdaQueryWrapper<UserFavoriteEntity>().eq(UserFavoriteEntity::getUserId, currentUserId)));
        toolSummary.put("coupon", userCouponService.count(new LambdaQueryWrapper<UserCouponEntity>().eq(UserCouponEntity::getUserId, currentUserId).eq(UserCouponEntity::getStatus, 0)));
        toolSummary.put("share", 0L);
        toolSummary.put("address", userAddressService.count(new LambdaQueryWrapper<UserAddressEntity>().eq(UserAddressEntity::getUserId, currentUserId)));
        toolSummary.put("refund", refundRequestService.count(new LambdaQueryWrapper<RefundRequestEntity>().eq(RefundRequestEntity::getUserId, currentUserId).eq(RefundRequestEntity::getStatus, "PENDING")));
        data.put("toolSummary", toolSummary);

        return ApiResponse.ok(data);
    }
    
    @PostMapping("/avatar/upload")
    public ApiResponse<String> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestAttribute(value = "currentUserId", required = false) Long currentUserId) {
        if (currentUserId == null) {
            return ApiResponse.error(401, "未登录");
        }
        
        if (file.isEmpty()) {
            return ApiResponse.error("文件为空");
        }
        
        try {
            // 获取项目根目录
            String projectRoot = System.getProperty("user.dir");
            File userDir = new File(projectRoot, "uploads/users/" + currentUserId);
            File avatarDir = new File(userDir, "avatar");
            if (!avatarDir.exists()) {
                avatarDir.mkdirs();
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String extension = originalFilename != null && originalFilename.contains(".") 
                ? originalFilename.substring(originalFilename.lastIndexOf(".")) 
                : ".jpg";
            String filename = UUID.randomUUID().toString() + extension;
            File destFile = new File(avatarDir, filename);
            
            // 保存文件
            file.transferTo(destFile);
            
            // 返回相对路径
            String avatarUrl = "/uploads/users/" + currentUserId + "/avatar/" + filename;
            
            // 更新用户头像
            UserEntity user = userService.getById(currentUserId);
            if (user != null) {
                user.setAvatarUrl(avatarUrl);
                userService.updateById(user);
            }
            
            return ApiResponse.ok(avatarUrl);
        } catch (IOException e) {
            return ApiResponse.error("文件上传失败: " + e.getMessage());
        }
    }
}


